import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:spree/utils/utils.dart';

import '../../../widgets/box-shadow.dart';
import '../../../widgets/vip_rectangle_box.dart';
import '../../orderHistory/history_table.dart';

class Statistics extends StatefulWidget {
  Statistics({Key? key}) : super(key: key);

  @override
  State<Statistics> createState() => _StatisticsState();
}

class _StatisticsState extends State<Statistics> {
  String _startTime = '';
  String gameType = "Invitation Bonus";
  String _endTime = '';
  List _gamesType = [
    {'label': 'Upgrade Reward', 'isCheck': true},
    {'label': 'Betting Commission', 'isCheck': false},
    {'label': 'Invitation Bonus', 'isCheck': false},
  ];
  String _selectNum = '10';
  @override
  Widget build(BuildContext context) {
    return BoxShadowContainer(
      padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
      child: Column(
        children: [
          VipRectangleBox(
            padding: EdgeInsets.all(12),
            color: Color(0xFF331F69),
            onTap: () async {
              DateTime dateTime = await _showDatePicker();
              setState(() {
                _startTime =
                    '${dateTime.year}-${dateTime.month}-${dateTime.day}';
              });
            },
            child: Row(
              children: [
                Icon(Icons.date_range, color: Color(0xFFB0AFEC)),
                Container(
                  margin: EdgeInsets.only(left: 12),
                  child: Text(
                    'start time:   $_startTime',
                    style: TextStyle(color: Color(0xFFB0AFEC)),
                  ),
                ),
              ],
            ),
          ),
          VipRectangleBox(
            margin: EdgeInsets.only(top: 20),
            padding: EdgeInsets.all(12),
            color: Color(0xFF331F69),
            onTap: () async {
              DateTime dateTime = await _showDatePicker();
              setState(() {
                _endTime = '${dateTime.year}-${dateTime.month}-${dateTime.day}';
              });
            },
            child: Row(
              children: [
                Icon(Icons.date_range, color: Color(0xFFB0AFEC)),
                Container(
                  margin: EdgeInsets.only(left: 12),
                  child: Text(
                    'end time:   $_endTime',
                    style: TextStyle(color: Color(0xFFB0AFEC)),
                  ),
                )
              ],
            ),
          ),
          VipRectangleBox(
            margin: EdgeInsets.only(top: 20),
            color: Color(0xFF331F69),
            child: ExpansionTile(
              initiallyExpanded: false,
              collapsedIconColor: Colors.white,
              iconColor: Colors.white,
              title: Text(
                gameType,
                style: TextStyle(color: Colors.white),
              ),
              children: _createExpansionPanel(_gamesType),
            ),
          ),
          VipRectangleBox(
            margin: EdgeInsets.only(top: 20),
            color: Color(0xFF331F69),
            child: ExpansionTile(
              initiallyExpanded: false,
              collapsedIconColor: Colors.white,
              iconColor: Colors.white,
              title: Text(
                _selectNum,
                style: TextStyle(color: Colors.white),
              ),
              children: _createNumberExpansionPanel(["10", "20", "30", "40"]),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 20, bottom: 20),
            height: 50,
            width: Utils().getScreenWidth(context),
            child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Color(0xFF7E68FF)),
                ),
                onPressed: () {
                  checkDate();
                },
                child: Text('Search')),
          ),
          HistoryTable(
            cellWidth: (Utils().getScreenWidth(context) - 30) / 3,
            data: [],
            dataKeys: ['bonus', 'user', 'time'],
            header: ['Bonus', 'User', 'Time'],
            dataLength: 3,
          )
        ],
      ),
    );
  }

  void checkDate() {
    var nowTime = DateTime.now();
    if (_startTime == '' || _startTime == null) {
      _startTime = nowTime.year.toString() +
          "-" +
          nowTime.month.toString() +
          "-" +
          nowTime.day.toString();
    }

    if (_endTime == '' || _endTime == null) {
      _endTime = nowTime.year.toString() +
          "-" +
          nowTime.month.toString() +
          "-" +
          nowTime.day.toString();
    }

    if (_startTime != "" && _endTime != "") {
      //需要判断时间是否合适
      var startDate = DateFormat("yyyy-MM-dd").parse(_startTime);
      var endDate = DateFormat("yyyy-MM-dd").parse(_endTime);
      if (endDate.isBefore(startDate)) {
        EasyLoading.showToast("结束日期必须比开始日期大");
        return;
      }
    }
  }

  List<Widget> _createExpansionPanel(List valueNotifier) {
    List<Widget> tiles = valueNotifier.asMap().keys.map((i) {
      return GestureDetector(
        onTap: () {
          setState(() {
            for (var i = 0; i < valueNotifier.length; i++) {
              valueNotifier[i]['isCheck'] = false;
            }
            valueNotifier[i]['isCheck'] = !valueNotifier[i]['isCheck'];
            gameType = valueNotifier[i]['label'];
          });
        },
        child: ListTile(
          trailing: valueNotifier[i]['isCheck']
              ? Icon(
                  Icons.check,
                  color: Color(0xffB0AFEC),
                )
              : null,
          title: Text(
            valueNotifier[i]['label'],
            style: TextStyle(color: Color(0xffB0AFEC)),
          ),
        ),
      );
    }).toList();

    return tiles;
  }

  List<Widget> _createNumberExpansionPanel(List valueNotifier) {
    List<Widget> tiles = valueNotifier.map((i) {
      return GestureDetector(
        onTap: () {
          setState(() {
            _selectNum = i;
          });
        },
        child: ListTile(
          trailing: _selectNum == i
              ? Icon(
                  Icons.check,
                  color: Color(0xffB0AFEC),
                )
              : null,
          title: Text(
            i,
            style: TextStyle(color: Color(0xffB0AFEC)),
          ),
        ),
      );
    }).toList();

    return tiles;
  }

  Future _showDatePicker() {
    Completer<DateTime> c = Completer();
    DatePicker.showDatePicker(
      context,
      showTitleActions: true,
      currentTime: DateTime.now(),
      locale: LocaleType.zh,
      minTime: DateTime(2018, 3, 5),
      maxTime: DateTime.now(),
      onConfirm: (date) {
        c.complete(date);
      },
    );
    return c.future;
  }
}
